if (LLVM_ENABLE_SPHINX)
    find_package(Sphinx REQUIRED)
endif()

function (build_sphinx_target builder project target_name)
    cmake_parse_arguments(ARG "" "SOURCE_DIR;DOXYGEN_XML_DIR" "DEPENDS" ${ARGN})

    set(SPHINX_BUILD_DIR "${CMAKE_CURRENT_BINARY_DIR}/${builder}")
    set(SPHINX_DOC_TREE_DIR "${CMAKE_CURRENT_BINARY_DIR}/_doctrees-${project}-${builder}")
    set(SPHINX_TARGET_NAME docs-${project}-${builder})
    set(${target_name} ${SPHINX_TARGET_NAME} PARENT_SCOPE)
    if (NOT ARG_SOURCE_DIR)
        set(ARG_SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/source")
    endif()

    add_custom_target(${SPHINX_TARGET_NAME}
            COMMAND ${SPHINX_EXECUTABLE}
            -b ${builder}
            -Dbreathe_projects.ELD="${ARG_DOXYGEN_XML_DIR}" # This is needed to hook sphinx up with the information generated by doxygen
            -d "${SPHINX_DOC_TREE_DIR}"
            -q # Quiet: no output other than errors and warnings.
            "${ARG_SOURCE_DIR}" # Source
            "${SPHINX_BUILD_DIR}" # Output
            DEPENDS eld-api-docs
            COMMENT
            "Generating ${builder} Sphinx documentation for ${project} into \"${SPHINX_BUILD_DIR}\"")
    add_dependencies(${SPHINX_TARGET_NAME} eld-api-docs ${ARG_DEPENDS})
endfunction()